# -*- coding: utf-8 -*-
# @Time     : 2021/12/1 15:54
# @Author   : wljess
# @File     : 互斥锁.py
# @Describe : 
# @Software : PyCharm

import time
from threading import Thread, Lock, enumerate


num = 1000
lock = Lock()


def task1(n):
    with lock:
        global num
        for _ in range(n):
            num -= 1
        print("----in task1, g_num is %d---" % num)


def task2(n):
    with lock:
        global num
        for _ in range(n):
            num += 1
        print("----in task2, g_num is %d---" % num)


if __name__ == '__main__':
    t = Thread(target=task1, args=(1000000, ))
    t1 = Thread(target=task2, args=(1000000, ))
    t.start()
    t1.start()
    # 确保子线程都运行结束
    while len(enumerate()) != 1:
        time.sleep(1)

    print("2个线程对同一个全局变量操作之后的最终结果是:%s" % num)

